﻿/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 3/1/2011
 * Time: 8:30 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using TomatoSynchronizer.Entities;
using TomatoSynchronizer.Store;
using HtmlAgilityPack;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace TomatoSynchronizer.Synchronizer
{
	/// <summary>
	/// Description of InformationSynchronizer
	/// </summary>
	public static class InformationSynchronizer
	{
		public static void Synchronize(Site siteSrc,Site siteDest,HtmlWeb client,SyncDirection direction)
		{
			switch(direction)
			{
				case SyncDirection.Download:
					UpLoadItems(siteDest,siteSrc,client,direction);
					break;
				case SyncDirection.Upload:
					UpLoadItems(siteSrc,siteDest,client,direction);
					break;
				case SyncDirection.DownloadAndUpload:
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					break;
				case SyncDirection.UploadAndDownload:
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					break;
				case SyncDirection.Synchronize:
					InformationStore InformationStoreDest = new InformationStore(siteDest,client);
					InformationStoreDest.Truncate();
					
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					break;
			}
		}
		
		private static void UpLoadItems(Site _siteSrc,Site _siteDest,HtmlWeb client,SyncDirection direction)
		{
			InformationStore InformationStoreSrc = new InformationStore(_siteSrc,client);
			InformationStore InformationStoreDest = new InformationStore(_siteDest,client);
			
			Information[] InformationesSrc =  InformationStoreSrc.LoadItems();
			Information[] InformationesDest =  InformationStoreDest.LoadItems();
			
			MappingStore mappingStoreSrc = new MappingStore(_siteSrc,_siteDest,"info_id");
			MappingStore mappingStoreDest = new MappingStore(_siteDest,_siteSrc,"info_id");
			
			mappingStoreSrc.Clean<Information>(InformationStoreSrc,InformationStoreDest);
			mappingStoreDest.Clean<Information>(InformationStoreDest,InformationStoreSrc);
			
			MappingStore mappingStore = new MappingStore(_siteSrc,_siteDest,"languages_id");
			
			List<Information> alreadySynchronized = new List<Information>();
			
			foreach(Information InformationSrc in InformationesSrc)
			{
				//we assume the Information is not yet synchronized
				bool synchronized = false;
				
				//we check if a mapping already exists for this Information in the destination store
				foreach(Mapping mapping in mappingStoreSrc.Mappings)
				{
					if(mapping.SrcValue == InformationSrc.articles_id && synchronized == false)
					{
						if(!string.IsNullOrEmpty(mapping.DestValue))
						{
							//this Information already exists in the destination store
							//we check if everything changed since the last synchronization
							Information InformationDest = InformationStoreDest.GetItem(mapping.DestValue);
							if(!string.IsNullOrEmpty(InformationDest.articles_id))
							{
								synchronized = SynchronizeItem(InformationSrc,InformationDest);
							}
							else
							{
								//the mapping exists, but the Information has been deleted in the destination store
								//we set a flag that this mapping does not exists anymore
								mapping.Exists = false;
							}
						}
					}
				}
				
				if(!synchronized)
				{
					//there is no mapping, we check if this Information already exists in the destination store
					foreach(Information InformationDest in InformationesDest)
					{
						foreach(Mapping mapping in mappingStore.Mappings)
						{
							try
							{
								if(InformationSrc.articles_names["articles_name[" + mapping.SrcValue + "]"] == InformationDest.articles_names["articles_name[" + mapping.DestValue + "]"] && synchronized == false && !alreadySynchronized.Contains(InformationSrc))
								{
									//we get the 2 currencies from sites to get sure they really exist
									Information src = InformationSrc.Store.GetItem(InformationSrc.articles_id);
									Information dest = InformationDest.Store.GetItem(InformationDest.articles_id);
									
									if(!string.IsNullOrEmpty(src.articles_id))
									{
										if(!string.IsNullOrEmpty(dest.articles_id))
										{
											Mapping _mapping = new Mapping(InformationSrc.articles_id,InformationDest.articles_id,"info_id");
											mappingStoreSrc.Mappings.Add(_mapping);
											
											synchronized = SynchronizeItem(InformationSrc,InformationDest);
										}
										else
										{
											synchronized = false;
										}
									}
									else
									{
										synchronized = true;
									}
								}
							}
							catch (KeyNotFoundException)
							{
								
							}
						}
						
					}
				}
				
				if(!synchronized)
				{
					//no mapping the Information is new
					//we insert it in the destination store
					string remoteId = string.Empty;
															
					InformationSrc.articles_categories_id = "1";
					
					var languages = InformationStoreDest.site.GetLanguageStore().LoadItems();
					
					Dictionary<string, string> _articles_head_keywords_tags = new Dictionary<string, string>();
					Dictionary<string, string> _articles_head_desc_tags = new Dictionary<string, string>();
					Dictionary<string, string> _articles_descriptions = new Dictionary<string, string>();
					Dictionary<string, string> _articles_names = new Dictionary<string, string>();
					Dictionary<string, string> _articles_urls = new Dictionary<string, string>();
					Dictionary<string, string> _meta_descriptions = new Dictionary<string, string>();
					Dictionary<string, string> _meta_keywordss = new Dictionary<string, string>();
					Dictionary<string, string> _page_titles = new Dictionary<string, string>();
					
					MappingStore _mappingStore = new MappingStore(InformationSrc.Store.site,InformationStoreDest.site,"languages_id");
					foreach(Mapping mapping in _mappingStore.Mappings)
					{
						_articles_head_keywords_tags["articles_head_keywords_tag[" + mapping.DestValue + "]"] = InformationSrc.articles_head_keywords_tags["articles_head_keywords_tag[" + mapping.SrcValue + "]"];
						_articles_head_desc_tags["articles_head_desc_tag[" + mapping.DestValue + "]"] = InformationSrc.articles_head_desc_tags["articles_head_desc_tag[" + mapping.SrcValue + "]"];
						_articles_descriptions["articles_description[" + mapping.DestValue + "]"] = InformationSrc.articles_descriptions["articles_description[" + mapping.SrcValue + "]"];
						_articles_names["articles_name[" + mapping.DestValue + "]"] = InformationSrc.articles_names["articles_name[" + mapping.SrcValue + "]"];
						_articles_urls["articles_url[" + mapping.DestValue + "]"] = InformationSrc.articles_urls["articles_url[" + mapping.SrcValue + "]"];
						_meta_descriptions["meta_description[" + mapping.DestValue + "]"] = InformationSrc.meta_descriptions["meta_description[" + mapping.SrcValue + "]"];
						_meta_keywordss["meta_keywords[" + mapping.DestValue + "]"] = InformationSrc.meta_keywordss["meta_keywords[" + mapping.SrcValue + "]"];
						_page_titles["page_title[" + mapping.DestValue + "]"] = InformationSrc.page_titles["page_title[" + mapping.SrcValue + "]"];
					}
					
					var old_articles_head_keywords_tags = InformationSrc.articles_head_keywords_tags;
					var old_articles_head_desc_tags = InformationSrc.articles_head_desc_tags;
					var old_articles_descriptions = InformationSrc.articles_descriptions;
					var old_articles_names = InformationSrc.articles_names;
					var old_articles_urls = InformationSrc.articles_urls;
					var old_meta_descriptions = InformationSrc.meta_descriptions;
					var old_meta_keywordss = InformationSrc.meta_keywordss;
					var old_page_titles = InformationSrc.page_titles;
					
					InformationSrc.articles_head_keywords_tags = _articles_head_keywords_tags;
					InformationSrc.articles_head_desc_tags = _articles_head_desc_tags;
					InformationSrc.articles_descriptions = _articles_descriptions;
					InformationSrc.articles_names = _articles_names;
					InformationSrc.articles_urls = _articles_urls;
					InformationSrc.meta_descriptions = _meta_descriptions;
					InformationSrc.meta_keywordss = _meta_keywordss;
					InformationSrc.page_titles = _page_titles;
					
					remoteId = InformationStoreDest.InsertItem(InformationSrc);
					
					synchronized = remoteId != string.Empty;
					
					if(!synchronized)
					{
						throw new Exception("The Information " + InformationSrc.articles_id + " has not been synchronized");
					}										
					
					Mapping _mapping = new Mapping(InformationSrc.articles_id,remoteId,"info_id");
					mappingStoreSrc.Mappings.Add(_mapping);
					synchronized = true;
				}
				
				if(!synchronized)
				{
					throw new Exception("could not synchronize the Information " + InformationSrc.articles_id);
				}
				
				InformationStoreSrc.PersistItem(InformationSrc);
				alreadySynchronized.Add(InformationSrc);
			}
			
			mappingStoreSrc.Save();
			
			mappingStoreDest.Truncate();
			
			//we save the mappings in the destination MappingStore too
			foreach(Mapping mapping in mappingStoreSrc.Mappings)
			{
				if(mapping.Exists)
				{
					Mapping mappingDest = new Mapping(mapping.DestValue,mapping.SrcValue,mapping.Property);
					mappingStoreDest.Mappings.Add(mappingDest);
				}
			}
			
			mappingStoreDest.Save();
			
			//we check if the 2 MappingStore are synchronized
			if(mappingStoreSrc.Mappings.Count != mappingStoreDest.Mappings.Count)
			{
				throw new Exception("The mapping store are not synchronized");
			}
		}
		
		private static bool SynchronizeItem(Information InformationSrc,Information InformationDest)
		{
			bool synchronized = true;
			
			if(!InformationSrc.Equals(InformationDest))
			{
				synchronized = false;
				
				//we update the destination Information
				InformationSrc.language_id = InformationDest.language_id;
				InformationSrc.articles_id = InformationDest.articles_id;
				InformationSrc.articles_categories_id = InformationDest.articles_categories_id;
				
				var languages = InformationDest.Store.site.GetLanguageStore().LoadItems();
				
				Dictionary<string, string> _articles_head_keywords_tags = new Dictionary<string, string>();
				Dictionary<string, string> _articles_head_desc_tags = new Dictionary<string, string>();
				Dictionary<string, string> _articles_descriptions = new Dictionary<string, string>();
				Dictionary<string, string> _articles_names = new Dictionary<string, string>();
				Dictionary<string, string> _articles_urls = new Dictionary<string, string>();
				Dictionary<string, string> _meta_descriptions = new Dictionary<string, string>();
				Dictionary<string, string> _meta_keywordss = new Dictionary<string, string>();
				Dictionary<string, string> _page_titles = new Dictionary<string, string>();
				
				MappingStore mappingStore = new MappingStore(InformationSrc.Store.site,InformationDest.Store.site,"languages_id");
				foreach(Mapping mapping in mappingStore.Mappings)
				{
					_articles_head_keywords_tags["articles_head_keywords_tag[" + mapping.DestValue + "]"] = InformationSrc.articles_head_keywords_tags["articles_head_keywords_tag[" + mapping.SrcValue + "]"];
					_articles_head_desc_tags["articles_head_desc_tag[" + mapping.DestValue + "]"] = InformationSrc.articles_head_desc_tags["articles_head_desc_tag[" + mapping.SrcValue + "]"];
					_articles_descriptions["articles_description[" + mapping.DestValue + "]"] = InformationSrc.articles_descriptions["articles_description[" + mapping.SrcValue + "]"];
					_articles_names["articles_name[" + mapping.DestValue + "]"] = InformationSrc.articles_names["articles_name[" + mapping.SrcValue + "]"];
					_articles_urls["articles_url[" + mapping.DestValue + "]"] = InformationSrc.articles_urls["articles_url[" + mapping.SrcValue + "]"];
					_meta_descriptions["meta_description[" + mapping.DestValue + "]"] = InformationSrc.meta_descriptions["meta_description[" + mapping.SrcValue + "]"];
					_meta_keywordss["meta_keywords[" + mapping.DestValue + "]"] = InformationSrc.meta_keywordss["meta_keywords[" + mapping.SrcValue + "]"];
					_page_titles["page_title[" + mapping.DestValue + "]"] = InformationSrc.page_titles["page_title[" + mapping.SrcValue + "]"];
				}
				
				InformationSrc.articles_head_keywords_tags = _articles_head_keywords_tags;
				InformationSrc.articles_head_desc_tags = _articles_head_desc_tags;
				InformationSrc.articles_descriptions = _articles_descriptions;
				InformationSrc.articles_names = _articles_names;
				InformationSrc.articles_urls = _articles_urls;
				InformationSrc.meta_descriptions = _meta_descriptions;
				InformationSrc.meta_keywordss = _meta_keywordss;
				InformationSrc.page_titles = _page_titles;
				
				synchronized = InformationDest.Store.UpdateItem(InformationSrc);
			}
			
			return synchronized;
		}
		
		private static string UploadItem(InformationStore InformationStoreDest,Information Information)
		{
			string remoteId = string.Empty;
			
			remoteId = InformationStoreDest.InsertItem(Information);
			
			return remoteId;
		}
	}
}
